<script setup lang="ts">
import { onMounted, ref} from 'vue'
import { Edit,Delete,User,Plus} from '@element-plus/icons-vue'
import { getAllRoleListAPI ,addRoleAPI,updateRoleAPI,deleteRoleAPI } from '@/api/permission/role.ts'
import { getMenuListByRoleIdAPI,assignPermissionAPI} from '@/api/permission/menu.ts'
import type { RoleItem,AddOrUpdateRoleParams } from '@/types/permission/role'
import { ElMessage } from 'element-plus'
import type { MenuItem } from '@/types/permission/menu'
import { filterTreeLast } from '@/utils/filterTreeLast'

// 添加/更新角色弹框

// 分页参数
const currentPageParams = ref({
    page: 1,
    pageSize: 5,
    total: 10
})

// 角色列表
const roleList = ref<RoleItem[]>([])

// 获取角色列表
const getRoleList = async() => {
    loading.value = true
    const res = await getAllRoleListAPI(currentPageParams.value.page, currentPageParams.value.pageSize,searchKeyword.value)
    console.log(res);
    roleList.value = res.data.records
    currentPageParams.value.total = res.data.total
    loading.value = false
}

// 切换页码
const changePage = (page: number) => {
    currentPageParams.value.page = page
    getRoleList()
}

// 切换每页条数
const changePageSize = (pageSize: number) => {
    currentPageParams.value.pageSize = pageSize
    getRoleList()
}

// 加载效果
const loading = ref<boolean>(false)  


// 搜索关键字
const searchKeyword = ref<string>('')


// 搜索
const search = () => {
    getRoleList()
}

// 重置
const reset = () => {
    searchKeyword.value = ''
    getRoleList()
}

// 添加职位弹框显示
const addRoleDialogShow = ref<boolean>(false)

// 添加角色
const addRole = () => {
    addRoleDialogShow.value = true
    dialogTitle.value = "添加角色"
}

// 编辑角色
const editRole = (row: RoleItem) => {
    dialogTitle.value = "编辑角色"
    addRoleDialogShow.value = true
    addRoleFrom.value = row
}

// 弹框标题
const dialogTitle = ref<string>('添加角色')

// 添加弹框表单数据
const addRoleFrom = ref<AddOrUpdateRoleParams>({
    roleName: ''
})

// 表单对象
const addRoleFormRef = ref<any>(null)

// 校验规则
const addRoleRules = {
    roleName: [
        {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur',
        },
        {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
        }
    ]
}

// 添加/更新角色确认
const addORupdateRoleConfirm = () => {
    addRoleFormRef.value.validate(async (valid: boolean) => {
        if(valid) {
            // 添加角色
            if(dialogTitle .value === "添加角色")  {
                // 发送请求添加角色
                const res = await addRoleAPI(addRoleFrom.value)
                // console.log(res);
                if(res.code === 200) {
                    ElMessage.success("添加成功")
                    // 刷新列表
                    getRoleList()
                    // 关闭弹框
                    addORupdateRoleCancel()
                    // 更新数据
                    getRoleList()
                }
            }else if (dialogTitle.value === "编辑角色") {
                const res = await updateRoleAPI(addRoleFrom.value)
                // console.log(res);
                if(res.code === 200) {
                    ElMessage.success("更新成功")
                    // 刷新列表
                    getRoleList()
                    // 关闭弹框
                    addORupdateRoleCancel()
                    // 更新数据
                    getRoleList()
                }
            }
        }
    })
}

// 添加/更新角色取消
const addORupdateRoleCancel = () => {
    addRoleDialogShow.value = false
    addRoleFormRef.value.resetFields()
}

// 删除角色
const deleteRole = async(id: string | number)  => {
    // 发送请求
    const res = await deleteRoleAPI(id as number)
    // console.log(res);
    if(res.code === 200) {
        ElMessage.success("删除成功")
        // 刷新列表
        getRoleList()
        // 关闭弹框
        addORupdateRoleCancel()
        // 更新数据
        getRoleList()
    }
}

// 分配权限组件显示
const drawerMenu = ref<boolean>(false)

// 权限数据
const menuList = ref<MenuItem[]>([])

// 已选中的权限数据
const selectMenuIdList = ref<MenuItem[]>([])

// 选择中角色
const selectRole = ref<RoleItem>()

// 分配权限
const assignMenu = async(row: RoleItem) => {
    // 保存当前角色
    selectRole.value = row
    // 发送请求获取菜单数据
    const res = await getMenuListByRoleIdAPI(row.id as number)
    // console.log(res);
    menuList.value = res.data
    // 过滤第四层的菜单的数据
    selectMenuIdList.value = (filterTreeLast(menuList.value,[])).map(item => item.id)
    // 打开分配权限组件
    drawerMenu.value = true
    console.log(selectMenuIdList.value);
    
}

// 树形组件配置项
const defaultProps = {
  children: 'children',
  label: 'name',
}

// 树形组件像
const treeRef = ref<any>(null)

// 分配权限确认
const assignMenuConfirm = async() => {
    // 获取选中节点id
    const idArr = treeRef.value && treeRef.value?.getCheckedKeys().concat(treeRef.value?.getHalfCheckedKeys())
    // 发送请求将选中权限id保存
    const res = await assignPermissionAPI(selectRole.value?.id as number,idArr)
    if(res.code === 200) {
        ElMessage.success("分配权限成功")
        // 关闭分配权限组件
        assignMenuCancel()
        // 刷新界面
        window.location.reload()
    }
}

// 分配权限取消
const assignMenuCancel = () => {
    // 关闭分配权限组件
    drawerMenu.value = false
    selectRole.value = undefined
    menuList.value = []
    selectMenuIdList.value = []
}



// 初始化
onMounted(() => {
    getRoleList()
})



</script>
<template>
    <div class="user">
        <el-card style="height: 80px">
            <el-form inline labe-width="100px" class="searchForm">
                <el-form-item label="职位搜索:">
                    <el-input v-model="searchKeyword "  placeholder="请输入关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :disabled="searchKeyword === ''"  @click="search">搜索</el-button>
                    <el-button  @click="reset" :disabled="searchKeyword === ''" type="primary">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card style="margin-top: 20px;">
            <el-row>
                <el-button v-disabled="'btn.Role.add'" size="large" type="primary"  @click="addRole" :icon="Plus">添加角色</el-button>
            </el-row>
            <el-table v-loading="loading" :data="roleList" stripe border  style="margin-top: 20px;">
                <el-table-column  align="center" type="index" label="序号" width="60px"></el-table-column>
                <el-table-column prop="id" align="center" label="id" width="100px"></el-table-column>
                <el-table-column prop="roleName" align="center" show-overflow-tooltip label="用户角色" ></el-table-column>
                <el-table-column prop="createTime" show-overflow-tooltip align="center" label="创建时间" ></el-table-column>
                <el-table-column prop="updateTime" show-overflow-tooltip align="center" label="更新时间" ></el-table-column>
                <el-table-column width="360px" align="center" label="操作" >
                    <template v-slot="{ row }">
                        <el-button v-disabled="'btn.Role.add'"  @click="assignMenu(row)" :data="row" type="primary" :icon="User" size="small" >分配权限</el-button>
                        <el-button  v-disabled="'btn.Role.update'"  type="primary" :icon="Edit" size="small" @click="editRole(row)">编辑</el-button>
                        <el-popconfirm @confirm="deleteRole(row.id)" title="确定要删除该角色吗?" confirm-button-text="确定" cancel-button-text="取消">
                            <template #reference>
                                <el-button v-disabled="'btn.Role.remove'"  type="primary" :icon="Delete" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
            style="margin: 10px 0;"
            v-model:current-page="currentPageParams.page"
            v-model:page-size="currentPageParams.pageSize"
            :background="true"
            :page-sizes="[3,5, 10, 20]"
            layout=" prev, pager, next, jumper,-> ,total, sizes"
            :total="currentPageParams.total"
            @size-change="changePageSize"
            @current-change="changePage"
            
            />
        </el-card>

        <!-- 对话框组件 -->
        <el-dialog @close="addORupdateRoleCancel"  v-model="addRoleDialogShow" :title="dialogTitle" style="max-width: 500px;" >
            <el-form  :rules="addRoleRules" ref="addRoleFormRef" :model="addRoleFrom" label-width="100px" >
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleFrom.roleName" placeholder="请输入角色名称"></el-input>
                </el-form-item>
            </el-form>
            <el-row style="justify-content: center;">
                <el-button type="primary"  @click="addORupdateRoleCancel">取消</el-button>
                <el-button type="primary" @click="addORupdateRoleConfirm">确认</el-button>
            </el-row>
        </el-dialog>
        <!-- 对话框组件 -->

        <!-- 分配菜单权限组件 -->
        <el-drawer v-model="drawerMenu" title="分配权限" >
            <el-row style="margin-bottom: 10px;"> 
                <el-button type="success" @click="assignMenuConfirm">确认</el-button>
                <el-button type="primary" @click="assignMenuCancel">取消</el-button>
            </el-row>
            <el-tree
                style="max-width: 600px"
                :data="menuList"
                show-checkbox
                node-key="id"
                :default-expanded-keys="selectMenuIdList"
                :default-checked-keys="selectMenuIdList"
                :props="defaultProps"
                ref="treeRef"
            />
        </el-drawer>
        <!-- 分配菜单权限组件 -->
    </div>
</template>



<style scoped>
.searchForm {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
}
</style>